package cn.iocoder.yudao.module.product.service.calculation;

import cn.iocoder.yudao.module.product.controller.admin.calculation.vo.EmissionCalculationCreateReqVO;
import cn.iocoder.yudao.module.product.controller.admin.calculation.vo.EmissionCalculationUpdateReqVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.product.dal.dataobject.calculation.EmissionCalculationDO;

import cn.iocoder.yudao.module.product.convert.calculation.EmissionCalculationConvert;
import cn.iocoder.yudao.module.product.dal.mysql.calculation.EmissionCalculationMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.*;

/**
 * 排放源-核算关联 Service 实现类
 *
 * @author wcl
 */
@Service
@Validated
public class EmissionCalculationServiceImpl implements EmissionCalculationService {

    @Resource
    private EmissionCalculationMapper emissionCalculationMapper;

    @Override
    public Long createEmissionCalculation(EmissionCalculationCreateReqVO createReqVO) {
        // 插入
        EmissionCalculationDO emissionCalculation = EmissionCalculationConvert.INSTANCE.convert(createReqVO);
        QueryWrapper<EmissionCalculationDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("emission_id", createReqVO.getEmissionId())
                    .eq("process_id", createReqVO.getProcessId())
                    .eq("calculation_id", createReqVO.getCalculationId());
        EmissionCalculationDO emissionCalculationFlag = emissionCalculationMapper.selectOne(queryWrapper);
        if (emissionCalculationFlag != null){
            emissionCalculationMapper.update( emissionCalculation , queryWrapper);
        }else {
            emissionCalculationMapper.insert(emissionCalculation);
        }
        // 返回
        return emissionCalculation.getId();
    }

    @Override
    public void updateEmissionCalculation(EmissionCalculationUpdateReqVO updateReqVO) {
        // 校验存在
        validateEmissionCalculationExists(updateReqVO.getId());
        // 更新
        EmissionCalculationDO updateObj = EmissionCalculationConvert.INSTANCE.convert(updateReqVO);
        emissionCalculationMapper.updateById(updateObj);
    }

    @Override
    public void deleteEmissionCalculation(Long id) {
        // 校验存在
        validateEmissionCalculationExists(id);
        // 删除
        emissionCalculationMapper.deleteById(id);
    }

    private void validateEmissionCalculationExists(Long id) {
        if (emissionCalculationMapper.selectById(id) == null) {
            throw exception(EMISSION_CALCULATION_NOT_EXISTS);
        }
    }

    @Override
    public EmissionCalculationDO getEmissionCalculation(Long id) {
        return emissionCalculationMapper.selectById(id);
    }

}
